<template>
  <div class="common-wrap">
    <QueryForm
      ref="conditionForm"
      module="product"
      :searchBtnLoading="loading"
      v-model:searchForm="searchForm"
      v-model:search-column="searchColumn"
      @handle-search="onSearch"
    />
    <div class="common-box">
      <el-row style="height: 40px" class="con-button-rows">
        <ButtonGroup
          :disabledDelete="multipleSelection.length === 0"
          :disabledEdit="multipleSelection.length !== 1"
          :hasPermiAdd="['common:product:add']"
          :hasPermiDelete="['common:product:delete']"
          :hasPermiEdit="['common:product:edit']"
          @add="onAdd"
          @edit="onEdit"
          @delete="onDelete"
        ></ButtonGroup>
      </el-row>
      <MyTable
        tableId="product"
        :columns="columns"
        :dataSource="dataSource"
        :loading="loading"
        :pageVo="pageVo"
        ref="commonTable"
        moduleName="product"
        @handleSelectionChange="handleSelectionChange"
        @handle-page-change="handlePageChange"
      ></MyTable>
    </div>
    <el-drawer
      v-model="drawer"
      direction="rtl"
      size="80%"
      resizable
      :title="$t(currRow.productName || '产品信息')"
    >
      <MyForm
         v-if="drawer"
        ref="commonForm"
        v-model:formData="formData"
        v-model:columns="formColumns"
        :saveBtnLoading="saveBtnLoading"
        :formButtons="false"
        background="#fff"
        @cancel="drawer = false"
      >
      </MyForm>
    </el-drawer>
    <Add
      v-if="dialogVisible"
      v-model:visible="dialogVisible"
      :currRow="currRow"
      :isType="isType"
      @onSubmit="onSearch"
    ></Add>
  </div>
</template>

<script setup lang='tsx'>
import { ref, reactive, onMounted, onUnmounted, onActivated } from "vue";
import { useI18n } from "vue-i18n";
import Add from "./components/add.vue";
import * as api from "@/api/index.js";
import { ElMessage, ElMessageBox } from "element-plus";
import { hasPermi } from "@/utils/mUtils.js";
import {
  queryFormColumnFilters,
  getSubZhEn,
  tabelColumnFilters,
} from "@/utils/mUtils.js";
let { t } = useI18n();

defineOptions({
  name: "Product",
});
const pageVo = reactive({
  pageSize: 50,
  total: 10,
  currentPage: 1,
  status: true,
});
const loading = ref(true);
const dataSource = ref([]);
const columns = ref([
  {
    type: "checkbox",
    width: 50,
    align: "center",
    fixed: "left",
  },
  {
    title: "序号",
    type: "seq",
    width: 60,
    fixed: "left",
  },
  {
    field: "productName",
    title: "主产品名称",
    slots: {
      default: ({ row }) => {
        return [
          <el-button
            type="primary"
            link
            onClick={() => {
              onEditList(row);
            }}
          >
            {row.productName || ""}
          </el-button>,
        ];
      },
    },
  },
  {
    field: "capableLoadWeight",
    title: "可装重量(KG)",
  },
  {
    field: "capableLoadCbm",
    title: "可装方数(CBM)",
  },
  {
    field: "createByName",
    title: "创建人",
  },
  {
    field: "createTime",
    title: "创建时间",
  },
  {
    field: "updateByName",
    title: "更新人",
  },
  {
    field: "updateTime",
    title: "更新时间",
  },
]);
const searchForm = ref({});
const searchColumn = ref([
  {
    type: "label_input",
    label: "产品名称",
    prop: "productName",
  },
]);
const dialogVisible = ref(false);
const multipleSelection = ref([]);
const currRow = ref({});
const isType = ref("add");
const drawer = ref(false);
const commonForm = ref();
const formData = ref({
  detailsList: [],
});
const formColumns = ref([
  {
    title: "",
    structure: [
      {
        type: "tabel",
        prop: "detailsList",
        tableIndex: 0,
        height: 500,
        hasPermiEdit: ["common:product:detailsEdit"],
        hasPermiAdd: ["common:product:detailsAdd"],
        hasPermiDelete: ["common:product:detailsDelete"],
        columns: [
          {
            type: "checkbox",
            width: 50,
            fixed: "left",
            align: "center",
          },
          {
            field: "subProductName",
            title: "子产品名称",
            editRender: {},
            slots: { edit: "input_edit" },
            width: 120,
          },
          {
            field: "orderTypeCode",
            title: "订单类型",
            editRender: {},
            params: {
              options: [],
              change: (val, rowIndex, row, options) => {
                row.orderTypeName = val.option.label;
              },
              key: "subName",
              value: "subCode",
              label: "subName",
              transfer: true,
            },
            slots: { edit: "select_edit" },
            formatter: ({ cellValue, row }) => {
              return row.orderTypeName;
            },
            labelKey: {
              orderTypeName: "orderTypeName",
            },
            width: 100,
          },
          {
            field: "lineDetailsId",
            title: "干线名称",
            editRender: {},
            slots: { edit: "remoteSelect_edit" },
            params: {
              params: {
                searchKey: "searchKey",
                keyValue: "id",
                name: "code",
                abbreviation: "lineName",
                showCustomizedOption: true,
                displayKey: {
                  customizeLeft: "providerName",
                  customizeCenter: "loadingPortName",
                  customizeRight: "deliveryPortName",
                },
                queryId: true,
              },
              paramsKey: {
                lineCode: "lineCode",
                lineName: "lineName",
              },
              apiModule: api.default.common.trunkLine.queryLineDetailList,
              placeholder: "请选择干线名称",
            },
            formatter: ({ cellValue, row }) => {
              return row.lineDetailDesc;
            },
            labelKey: {
              lineDetailDesc: "lineDetailDesc",
            },
            span: 2,
          },
          {
            field: "goodsType",
            title: "货物类型",
            editRender: {},
            params: {
              multiple: true,
              options: [],
              change: (val, rowIndex, row, options) => {
                row.goodsTypeCode = val.value.join(",");
                row.goodsTypeName = options
                  .filter((item) => val.value.includes(item.subCode))
                  .map((item) => item.subName)
                  .join(",");
              },
              key: "subName",
              value: "subCode",
              label: "subName",
              transfer: true,
            },
            slots: { edit: "select_edit" },
            formatter: ({ cellValue, row }) => {
              return row.goodsTypeName;
            },
            labelKey: {
              goodsTypeName: "goodsTypeName",
            },
            width: 100,
          },
          {
            field: "includeTaxFlag",
            title: "是否包税",
            editRender: {},
            valueKey: {
              1: "是",
              0: "否",
              2: "其他",
            },
            params: {
              options: [
                {
                  label: "是",
                  value: 1,
                },
                {
                  label: "否",
                  value: 0,
                },
                {
                  label: "其他",
                  value: 2,
                },
              ],
              key: "value",
              value: "value",
              label: "label",
              transfer: true,
            },
            slots: { edit: "select_edit" },
            formatter: ({ cellValue }) => {
              return cellValue === 1
                ? "是"
                : cellValue === 0
                ? "否"
                : cellValue
                ? "其他"
                : "";
            },
            width: 100,
          },
          {
            field: "deliveryMethodCode",
            title: "派送方式",
            editRender: {},
            params: {
              options: [],
              change: (val, rowIndex, row, options) => {
                row.deliveryMethodName = val.option.label;
              },
              key: "subName",
              value: "subCode",
              label: "subName",
              transfer: true,
            },
            slots: { edit: "select_edit" },
            formatter: ({ cellValue, row }) => {
              return row.deliveryMethodName;
            },
            labelKey: {
              deliveryMethodName: "deliveryMethodName",
            },
            width: 100,
          },
          {
            field: "chargeMethodCode",
            title: "计费方式",
            editRender: {},
            params: {
              options: [],
              change: (val, rowIndex, row, options) => {
                row.chargeMethodName = val.option.label;
              },
              key: "subName",
              value: "subCode",
              label: "subName",
              transfer: true,
            },
            slots: { edit: "select_edit" },
            formatter: ({ cellValue, row }) => {
              return row.chargeMethodName;
            },
            labelKey: {
              chargeMethodName: "chargeMethodName",
            },
            width: 100,
          },
          {
            field: "calcWeightRuleId",
            title: "计重规则",
            editRender: {},
            slots: { edit: "remoteSelect_edit" },
            params: {
              params: {
                searchKey: "searchKey",
                keyValue: "id",
                name: "ruleName",
                showCustomizedOption: true,
                displayKey: {
                  calcBillType: "calcBillType",
                  calcType: "calcType",
                  calcWeightRuleName: "ruleName",
                },
                displayName: {
                  calcBillType: {
                    0: t("KGS计重"),
                    1: t("CBM计方"),
                  },
                  calcType: {
                    0: t("按票"),
                    1: t("按单件"),
                  },
                },
                queryId: true,
              },
              apiModule: api.default.common.weighing.queryList,
              placeholder: "请选择干线名称",
            },
            formatter: ({ cellValue, row }) => {
              return row.calcWeightRuleName;
            },
            labelKey: {
              calcWeightRuleName: "calcWeightRuleName",
            },
            width: 100,
          },
          {
            field: "overSizeRuleId",
            title: "超规规则",
            editRender: {},
            slots: { edit: "input_edit" },
            params: {
              type: "number",
            },
            width: 100,
          },
        ],
        editRules: {
          subProductName: [
            {
              required: true,
              message: t("请填写子产品名称"),
            },
          ],
          orderTypeCode: [
            {
              required: true,
              message: t("请选择订单类型"),
            },
          ],
          lineDetailsId: [
            {
              required: true,
              message: t("请选择干线名称"),
            },
          ],
          includeTaxFlag: [
            {
              required: true,
              message: t("请选择是否包税"),
            },
          ],
          deliveryMethodCode: [
            {
              required: true,
              message: t("请选择派送方式"),
            },
          ],
          chargeMethodCode: [
            {
              required: true,
              message: t("请选择计费方式"),
            },
          ],
        },
        multipleSelection: [],
        buttonType: ["add", "delete"],
        batchDelete: true,
        keepSource: true,
        changeEditNeedTrigger: false,
        keepSourceKey: "subProductName",
        tableId: "detailsList",
        onDelete: (black) => {
          onDeleteDetails(black);
        },
        handleEditClosed: (row, rowIndex, resolve, reject, black) => {
          save(row, rowIndex, resolve, reject, black);
        },
      },
    ],
  },
]);
const saveBtnLoading = ref(false);
onMounted(() => {
  onSearch();
  onGetSub();
});
const onGetSub = () => {
  getSubZhEn({
    code: "020,021,022,024",
  }).then((res) => {
    tabelColumnFilters(
      formColumns.value[0].structure[0].columns,
      "orderTypeCode"
    ).params.options = res["020"];
    tabelColumnFilters(
      formColumns.value[0].structure[0].columns,
      "deliveryMethodCode"
    ).params.options = res["021"];
    tabelColumnFilters(
      formColumns.value[0].structure[0].columns,
      "chargeMethodCode"
    ).params.options = res["022"];
    tabelColumnFilters(
      formColumns.value[0].structure[0].columns,
      "goodsType"
    ).params.options = res["024"];
  });
};
const list = () => {
  loading.value = true;
  api.default.common.product
    .list({
      ...searchForm.value,
      pageNum: pageVo.currentPage,
      pageSize: pageVo.pageSize,
    })
    .then((res) => {
      dataSource.value = res.rows;
      loading.value = false;
      pageVo.total = res.total;
    })
    .catch(() => {
      loading.value = false;
    });
};

const onAdd = () => {
  isType.value = "add";
  if (multipleSelection.value.length != 0) {
    currRow.value = multipleSelection.value[0];
  }
  dialogVisible.value = true;
};
const onEdit = () => {
  isType.value = "edit";
  currRow.value = multipleSelection.value[0];
  dialogVisible.value = true;
};
const onEditList = (row) => {
  currRow.value = { ...row };
  drawer.value = true;
  detailsList();
};
const onDelete = () => {
  const ids = multipleSelection.value.map((item) => item.id);
  ElMessageBox.confirm(t("是否确定删除当前选择数据？"), t("提示"), {
    confirmButtonText: t("确定"),
    cancelButtonText: t("取消"),
    type: "warning",
  })
    .then(() => {
      api.default.common.product.remove(ids).then(() => {
        ElMessage.success(t("删除成功"));
        onSearch();
      });
    })
    .catch(() => {});
};
const handleSelectionChange = (list) => {
  multipleSelection.value = list;
};
const handlePageChange = (val) => {
  const { currentPage, pageSize } = val;
  pageVo.currentPage = currentPage;
  pageVo.pageSize = pageSize;
  list();
};
const onSearch = () => {
  pageVo.currentPage = 1;
  list();
};
const detailsList = async () => {
  const { rows } = await api.default.common.product.detailsList({
    mainProductId: currRow.value?.id,
  });
  formData.value.detailsList = rows.map((item) => {
    return {
      ...item,
      goodsType: item.goodsTypeCode?.split(","),
    };
  });
};
const onDeleteDetails = (ids) => {
  api.default.common.product.detailsRemove(ids).then(() => {
    ElMessage.success(t("删除成功"));
    detailsList();
  });
};
const save = async (row, rowIndex, resolve, reject, black) => {
  try {
    if (!row.id) {
      await api.default.common.product.detailsAdd({
        ...row,
        mainProductId: currRow.value?.id,
      });
      detailsList();
      ElMessage.success(t("新增成功"));
    } else {
      await api.default.common.product.detailsEdit(row);
      detailsList();
      ElMessage.success(t("修改成功"));
    }
    resolve();
  } catch (e) {
    reject();
  }
};
</script>

<style lang="scss" scoped>
.pcMenu {
  height: 100%;
  width: 100%;
  background: #fff;
}
</style>